package com.xishu.controller;

import com.xishu.annotation.valid.Admin;
import com.xishu.annotation.valid.MethodValidator;
import com.xishu.entity.Company;
import com.xishu.entity.customer.NoticeHistory;
import com.xishu.entity.customer.Quota;
import com.xishu.response.ResponseData;
import com.xishu.service.CommonService;
import com.xishu.service.CompanyService;
import com.xishu.service.CustomerService;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 配额管理
 */
@RestController
public class QuotaController {
    private CustomerService customerService = CustomerService.getInstance();
    private CompanyService companyService = CompanyService.getInstance();
    private CommonService commonService = CommonService.getInstance();

    @ApiOperation(value = "查询配额")
    @PutMapping(value = ("/company/quota"), produces = ("application/json;charset=UTF-8"))
    public ResponseData search(@RequestBody Quota quota) throws Exception {
        Long companyId = quota.getCompanyId();
        companyService.findCompanyById(companyId);
        customerService.findQuotaOrCreate(companyId);
        return commonService.searchResponse(quota);
    }

    /**
     * 至少要是平台管理员才可以配额
     *
     * @param quota
     * @return
     */
    @MethodValidator(platManagerUser = true)
    @ApiOperation(value = "修改配额")
    @PutMapping(value = ("/company/quota/modify"), produces = ("application/json;charset=UTF-8"))
    @Admin
    public ResponseData modify(@RequestBody Quota quota) throws Exception {
        Long quotaId = quota.getId();
        Quota quotaInDb = customerService.findQuota(quotaId);

        if (quota.getSmsCanUsed() != null) {
            int smsCanUsed = quotaInDb.getSmsCanUsed();
            quota.setSmsCanUsed(smsCanUsed + quota.getSmsCanUsed());

            //如果修改了配额，那么同步删除对应的发送历史，以方便后面再次发送
            {
                NoticeHistory noticeHistory = new NoticeHistory();
                noticeHistory.setCompanyId(quotaInDb.getCompanyId());
                noticeHistory.setEmail(false);
                noticeHistory.setPlan(true);
                commonService.searchAll(noticeHistory).forEach(history -> {
                    history.setFlagDelete(true);
                    commonService.directSave(history);
                });
            }
        }

        if (quota.getEmailCanUsed() != null) {
            Integer emailCanUsed = quotaInDb.getEmailCanUsed();
            quota.setEmailCanUsed(emailCanUsed + quota.getEmailCanUsed());

            //如果修改了配额，那么同步删除对应的发送历史，以方便后面再次发送
            {
                NoticeHistory noticeHistory = new NoticeHistory();
                noticeHistory.setCompanyId(quotaInDb.getCompanyId());
                noticeHistory.setEmail(true);
                noticeHistory.setPlan(true);
                commonService.searchAll(noticeHistory).forEach(history -> {
                    history.setFlagDelete(true);
                    commonService.directSave(history);
                });
            }
        }

        if (quota.getUnPlanSmsCanUsed() != null) {
            Integer unPlanSmsCanUsed = quotaInDb.getUnPlanSmsCanUsed();
            quota.setUnPlanSmsCanUsed(unPlanSmsCanUsed + quota.getUnPlanSmsCanUsed());

            if (quota.getUnPlanSmsCanUsed() <= 0) {
                Long companyId = quotaInDb.getCompanyId();
                Company company = companyService.findCompanyById(companyId);
                company.getCompanyConfig().setPhoneToken(false);
                commonService.save(company);
            }

            //如果修改了配额，那么同步删除对应的发送历史，以方便后面再次发送
            {
                NoticeHistory noticeHistory = new NoticeHistory();
                noticeHistory.setCompanyId(quotaInDb.getCompanyId());
                noticeHistory.setEmail(false);
                noticeHistory.setPlan(false);
                commonService.searchAll(noticeHistory).forEach(history -> {
                    history.setFlagDelete(true);
                    commonService.directSave(history);
                });
            }
        }

        if (quota.getUnPlanEmailCanUsed() != null) {
            Integer unPlanEmailCanUsed = quotaInDb.getUnPlanEmailCanUsed();
            quota.setUnPlanEmailCanUsed(unPlanEmailCanUsed + quota.getUnPlanEmailCanUsed());

            if (quota.getUnPlanEmailCanUsed() <= 0) {
                Long companyId = quotaInDb.getCompanyId();
                Company company = companyService.findCompanyById(companyId);
                company.getCompanyConfig().setEmailToken(false);
                commonService.save(company);
            }

            //如果修改了配额，那么同步删除对应的发送历史，以方便后面再次发送
            {
                NoticeHistory noticeHistory = new NoticeHistory();
                noticeHistory.setCompanyId(quotaInDb.getCompanyId());
                noticeHistory.setEmail(true);
                noticeHistory.setPlan(false);
                commonService.searchAll(noticeHistory).forEach(history -> {
                    history.setFlagDelete(true);
                    commonService.directSave(history);
                });
            }
        }

        return commonService.modifyObject(quota);
    }


}
